package com.passer.toolbox.tfile.command;

import com.passer.toolbox.common.util.file.FileUtils;

import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class FileRename {

    public void launcher() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要批量重名文件夹的父目录：");
        String sourceParentPath = scanner.next();
        System.out.println("输入原文件名：");
        String oldName = scanner.next();
        System.out.println("输入新文件名：");
        String newName = scanner.next();
        renameFolders(sourceParentPath, oldName, newName);
    }

    public void renameFolders(String sourceParentPath, String oldName, String newName) {
        File sourceParent = new File(sourceParentPath);
        if (!sourceParent.exists() || sourceParent.isFile()) {
            System.out.println(sourceParentPath + "：文件夹不存在");
            return;
        }
        Pattern compile = Pattern.compile(oldName);
        HashMap<String, List<String>> map = new HashMap<>();
        FileUtils.getFolderNames(sourceParent, map, compile);
        if (map.isEmpty()) {
            System.out.println(sourceParentPath + " 目录下无待重命名文件夹");
            return;
        }
        List<String> filePathList = new ArrayList<>();
        for (List<String> list : map.values()) {
            filePathList.addAll(list);
        }
        String separator = System.getProperty("os.name").startsWith("Windows") ? "\\\\" : "/";
        filePathList = filePathList.stream().sorted((o1, o2) -> {
            String[] o1Array = o1.split(separator);
            String[] o2Array = o2.split(separator);
            return Integer.compare(o2Array.length, o1Array.length);
        }).collect(Collectors.toList());
        for (String filePath : filePathList) {
            File file = new File(filePath);
            boolean renameTo = file.renameTo(new File(file.getParentFile(), newName));
            if (renameTo) {
                System.out.println("重命名：" + filePath);
            }
        }
    }
}
